#!/bin/bash

# 系统恢复脚本
# 从备份恢复数据库、代码和配置

set -e

BACKUP_DIR="/opt/backups/nanchang-tour"

echo "========================================"
echo "  系统恢复"
echo "========================================"
echo ""

# 列出可用备份
echo "可用备份:"
ls -1 "$BACKUP_DIR"/*.sql 2>/dev/null | sed 's|.*/||' | sed 's|\.sql$||' || {
    echo "未找到备份文件"
    exit 1
}
echo ""

read -p "请输入要恢复的备份名称（不含扩展名）: " BACKUP_NAME

if [ ! -f "$BACKUP_DIR/$BACKUP_NAME.sql" ]; then
    echo "错误: 备份文件不存在"
    exit 1
fi

read -p "确认恢复备份 $BACKUP_NAME? (y/N): " CONFIRM
if [ "$CONFIRM" != "y" ] && [ "$CONFIRM" != "Y" ]; then
    echo "取消恢复"
    exit 0
fi

# 1. 恢复数据库
echo ""
echo "[1/3] 恢复数据库..."
if [ -f "/opt/nanchang-tour/backend/.env" ]; then
    source /opt/nanchang-tour/backend/.env 2>/dev/null || true
    DB_NAME=${DB_NAME:-nanchang_tour}
    DB_USER=${DB_USER:-root}
    DB_PASSWORD=${DB_PASSWORD:-123456}
    DB_HOST=${DB_HOST:-localhost}
    
    mysql -u"$DB_USER" -p"$DB_PASSWORD" -h"$DB_HOST" "$DB_NAME" < "$BACKUP_DIR/$BACKUP_NAME.sql"
    echo "✓ 数据库恢复完成"
else
    echo "⚠ 无法读取数据库配置，跳过数据库恢复"
fi

# 2. 恢复代码
if [ -f "$BACKUP_DIR/$BACKUP_NAME-code.tar.gz" ]; then
    echo "[2/3] 恢复代码..."
    read -p "恢复代码将覆盖现有文件，确认继续? (y/N): " CONFIRM_CODE
    if [ "$CONFIRM_CODE" = "y" ] || [ "$CONFIRM_CODE" = "Y" ]; then
        tar -xzf "$BACKUP_DIR/$BACKUP_NAME-code.tar.gz" -C /opt
        echo "✓ 代码恢复完成"
    else
        echo "⚠ 跳过代码恢复"
    fi
fi

# 3. 恢复配置
if [ -f "$BACKUP_DIR/$BACKUP_NAME-config.tar.gz" ]; then
    echo "[3/3] 恢复配置文件..."
    read -p "恢复配置将覆盖现有配置，确认继续? (y/N): " CONFIRM_CONFIG
    if [ "$CONFIRM_CONFIG" = "y" ] || [ "$CONFIRM_CONFIG" = "Y" ]; then
        TEMP_DIR=$(mktemp -d)
        tar -xzf "$BACKUP_DIR/$BACKUP_NAME-config.tar.gz" -C "$TEMP_DIR"
        
        if [ -f "$TEMP_DIR/$BACKUP_NAME-config/.env" ]; then
            cp "$TEMP_DIR/$BACKUP_NAME-config/.env" /opt/nanchang-tour/backend/.env
        fi
        if [ -f "$TEMP_DIR/$BACKUP_NAME-config/nginx.conf" ]; then
            cp "$TEMP_DIR/$BACKUP_NAME-config/nginx.conf" /etc/nginx/sites-available/nanchang-tour
        fi
        if [ -f "$TEMP_DIR/$BACKUP_NAME-config/nanchang-tour.service" ]; then
            cp "$TEMP_DIR/$BACKUP_NAME-config/nanchang-tour.service" /etc/systemd/system/
            systemctl daemon-reload
        fi
        
        rm -rf "$TEMP_DIR"
        echo "✓ 配置文件恢复完成"
    else
        echo "⚠ 跳过配置恢复"
    fi
fi

echo ""
echo "========================================"
echo "  ✓ 恢复完成！"
echo "========================================"
echo ""
echo "建议重启服务:"
echo "  sudo systemctl restart nanchang-tour"
echo "  sudo systemctl restart nginx"
echo ""

